import {Component, NgModule, OnInit} from "@angular/core";
import { HttpServcie } from "../../service/http.service";
import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService, UploadFile} from "ng-zorro-antd";
import {TrainingPlanBean} from "./bean/trainingPlan.bean";
import {Config} from "../../service/config";
import * as moment from "moment";


@Component({
  selector: "trainingPlan-page",
  templateUrl: "trainingPlan.html",
  styleUrls: ["trainingPlan.scss"]
})

export class TrainingPlan {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) { }
  config = Config;
  trainingPlanBean : TrainingPlanBean = new TrainingPlanBean();
  trainingTypes = Config.TRAINING_TYPE;
  data: Array<any> = [];
  partyType : string = "";
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;
  startDate : string = "";
  endDate : string = "";
  planName : string = "";
  planType : string = "";
  //返回的集合
  dataList : any = [];
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  updateData: any = {};
  total = 0;
  //文件上传
  materialsFileList : UploadFile[] = []; //培训材料
  checkInTableFileList : UploadFile[] = []; //签到表
  testPaperFileList : UploadFile[] = []; //试卷
  ssFileList : UploadFile[] = []; //汇总表
  isVisible : boolean = false;
  uploadType : any;

  ngOnInit(){
    this.partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
    this.trainingPlanBean.pageSize = 10;
    this.trainingPlanBean.currentPage = 1;
    this.query();
  }

  query(){
    if(this.trainingPlanBean.startDate){
      this.trainingPlanBean.startDate = moment(this.trainingPlanBean.startDate).format("YYYYMMDD");
    } else{
      this.trainingPlanBean.startDate = null;
    }
    if(this.trainingPlanBean.endDate){
      this.trainingPlanBean.endDate = moment(this.trainingPlanBean.endDate).format("YYYYMMDD");
    }else{
      this.trainingPlanBean.endDate = null;
    }
    this.trainingPlanBean.leadUnitId = JSON.parse(window.localStorage.getItem("user")).partyId;
    this.httpService.queryTrainingPlan(this.trainingPlanBean).subscribe(data => {
      if (data.status == "200") {
        this.dataList = data.data.list;
        this.total = data.data.total;
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  add(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType == 2) {
      this._notification.create("warning", "提示", "功能测试中");
      return;
    }
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  update(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType == 2) {
      this._notification.create("warning", "提示", "功能测试中");
      return;
    }
      this.modelTitle = "修改";
      this.modal = 1;
      const updateList: any = [];

      this.dataList.forEach(element => {
        if (element.checked) {
          updateList.push(element);
          this.updateData = element;
        }
      });
      if (updateList.length > 1) {
        // 异常
        this._notification.create("warning", "警告提示", "只能选中一条数据！");
        return;
      }
      if (updateList.length == 0) {
        // 异常
        this._notification.create("warning", "警告提示", "请选中一条数据！");
        return;
      }
      this.currentModal = this.modalService.open({
        title: title,
        content: content,
        footer: footer,
        maskClosable: false,
        width: 800,
        style: {
          top: "20px"
        },
        onOk() {
          console.log("Click ok");
        }
      });
  }

  delete(){
    if (JSON.parse(window.localStorage.getItem("user")).partyType == 2) {
      this._notification.create("warning", "提示", "功能测试中");
      return;
    }
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }
    const deleteList: any = [];
    const thiss: any = this;
    this.dataList.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id);
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpService.deleteTrainingPlan({ ids: deleteList }); //批量删除
        ob.subscribe(
          data => {
            if (data.status == "200") {
              thiss.trainingPlanBean.currentPage = 1;
              thiss.query();
            } else {
              this._notification.create("error", "", data.message);
            }
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  //打开上传模态框 1：培训材料；2：培训签到表；3：培训试卷；4：考核汇总表
  uploadFile(data, type) {
    this.materialsFileList = [];
    this.checkInTableFileList = [];
    this.testPaperFileList = [];
    this.ssFileList = [];
    this.updateData = data;
    this.isVisible = true;
    this.uploadType = type;
    if (type == 1) {
      if (data.materials) {
        (data.materials + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP +
              this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111000,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.materialsFileList.push(file);
        })
      }
    }
    if (type == 2) {
      if (data.checkInTable) {
        (data.checkInTable + "").split(',').forEach(ele => {
          let file: UploadFile = {
            "thumbUrl": this.config.IP + this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111000,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.checkInTableFileList.push(file);
        })
      }
    }

    if (type == 3) {
      if (data.testPaper) {
        (data.testPaper + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP + this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.testPaperFileList.push(file);
        })
      }
    }

    if (type == 4) {
      if (data.summaryStatement) {
        (data.summaryStatement + "").split(',').forEach(ele => {
          let file: UploadFile = {
            thumbUrl: this.config.IP + this.config.API.getUpload + ele,
            uid: ele,
            size: 1231111,
            name: ele,
            type: '',
            response: {
              data: ele
            }
          }
          this.ssFileList.push(file);
        })
      }
    }
  }

  nzRemoveFile = (file: UploadFile) => {
    this.httpService.deleteUpload(file["response"]["data"]).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }

        if (this.uploadType == 1) {
          if (this.materialsFileList.length == 1) {
            this.materialsFileList = [];
            return;
          }
          this.materialsFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.materialsFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 2) {
          if (this.checkInTableFileList.length == 1) {
            this.checkInTableFileList = [];
            return;
          }
          this.checkInTableFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.checkInTableFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 2) {
          if (this.checkInTableFileList.length == 1) {
            this.checkInTableFileList = [];
            return;
          }
          this.checkInTableFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.checkInTableFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 3) {
          if (this.testPaperFileList.length == 1) {
            this.testPaperFileList = [];
            return;
          }
          this.testPaperFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.testPaperFileList.splice(index, 1);
            }
          });
        }

        if (this.uploadType == 4) {
          if (this.ssFileList.length == 1) {
            this.ssFileList = [];
            return;
          }
          this.ssFileList.forEach((element, index) => {
            if (element["thumbUrl"] == file.thumbUrl) {
              this.ssFileList.splice(index, 1);
            }
          });
        }

      },
      error => {
        this._notification.create("error", "", "请求超时！");
        return;
      }
    );
  };

//上传文件完成后的回调
  nzChangeFile(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      if (this.uploadType == 1) {
        this.materialsFileList.forEach(element => {
          alert(JSON.stringify(element));
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

      if (this.uploadType == 2) {
        this.checkInTableFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

      if (this.uploadType == 3) {
        this.testPaperFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

      if (this.uploadType == 4) {
        this.ssFileList.forEach(element => {
          element["thumbUrl"] =
            this.config.IP +
            this.config.API.getUpload +
            element["response"]["data"];
        });
      }

    }
  }

  uploadChange(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      if (info.file.response.status != "200") {
        this._notification.create(
          "error",
          "错误提示",
          info.file.response.message
        );
      } else {
        this._notification.create("success", "提示", "上传成功");
      }
      // Get this url from response in real world.
    }
  }

  //上传完了之后 提交数据
  updateUpload() {
    if (this.uploadType == 1) {
      let param = {
        id: this.updateData.id,
        materials : null
      }
      let list = [];
      this.materialsFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.materials = list.join(',');

      this.httpService.uploadMaterials(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.materialsFileList = [];
          this.query();
        }
      });
    }
    if (this.uploadType == 2) {
      let param = {
        id: this.updateData.id,
        checkInTable : null
      }
      let list = [];
      this.checkInTableFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.checkInTable = list.join(',');
      this.httpService.uploadCheckInTable(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.checkInTableFileList = [];
          this.query();
        }
      });
    }

    if (this.uploadType == 3) {
      let param = {
        id: this.updateData.id,
        testPaper: null
      }
      let list = [];
      this.testPaperFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.testPaper = list.join(',');
      this.httpService.uploadTestPaper(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.testPaperFileList = [];
          this.query();
        }
      });
    }

    if (this.uploadType == 4) {
      let param = {
        id: this.updateData.id,
        summaryStatement: null
      }
      let list = [];
      this.ssFileList.forEach(element => {
        list.push(element.response.data);
      });
      param.summaryStatement = list.join(',');
      this.httpService.uploadSummaryStatement(param).subscribe(data => {
        if (data.status == 200) {
          this._notification.create('success', '成功', '更新成功');
          this.isVisible = false;
          this.ssFileList = [];
          this.query();
        }
      });
    }

  }


  showTrainingPlanDetail(data) {
    this.router.navigate(["/home/training-plan-detail", data]);
  }

  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //分页处理
  nzPageSizeChange(event){
    this.trainingPlanBean.pageSize = event;
    this.trainingPlanBean.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.trainingPlanBean.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.trainingPlanBean.currentPage = event;
    this.query();
  }

  //添加返回
  addCall(event) {
    this.currentModal.destroy();
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

}
